package org.example.shardiing.config;

import cn.hutool.core.collection.CollUtil;
import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingValue;

import java.util.*;

/**
 * @author linshiqiang
 * @date 2025-06-14 11:35:00
 * @description 根据业务时间 服务编码 按年分表
 */
public class ServiceCodeHintShardingAlgorithm implements HintShardingAlgorithm<HitBusinessTimeDTO> {

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, HintShardingValue<HitBusinessTimeDTO> hintShardingValue) {
        String logicTableName = hintShardingValue.getLogicTableName();
        Collection<HitBusinessTimeDTO> values = hintShardingValue.getValues();
        Optional<HitBusinessTimeDTO> dtoOptional = values.stream().findFirst();
        if (dtoOptional.isEmpty()) {
            return List.of();
        }
        HitBusinessTimeDTO businessTimeDTO = dtoOptional.get();
        Long timestamp = businessTimeDTO.getTimestamp();
        int year = ShardingUtils.getYear(timestamp);
        List<String> serviceCodes = businessTimeDTO.getServiceCodes();
        if (CollUtil.isEmpty(serviceCodes)) {
            return List.of();
        }
        List<String> tableNames = new ArrayList<>();
        for (String serviceCode : serviceCodes) {
            String tableName = serviceCode + "_" + logicTableName + "_" + year;
            if (availableTargetNames.contains(tableName)) {
                tableNames.add(tableName);
            }
        }
        System.out.println("===================================================================>");
        System.out.println("命中..................................." + tableNames);
        System.out.println("===================================================================>");
        return tableNames;
    }

    @Override
    public String getType() {
        return "HINT_BUSINESS_CODE_AND_TIME";
    }

    @Override
    public void init(Properties props) {
        HintShardingAlgorithm.super.init(props);
    }

}
